{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 卷积神经网络（LeNet）\n",
    "\n",
    ":label:`sec_lenet`\n",
    "\n",
    "\n",
    "我们现在拥有组装所需的所有原料\n",
    "一个全功能的卷积神经网络。\n",
    "在我们第一次接触图像数据时，\n",
    "我们应用了多层感知器 (:numref:`sec_mlp_scratch`)\n",
    "到时装MNIST数据集中的服装图片。\n",
    "为了使这些数据适用于多层感知器，\n",
    "我们首先从 $28\\times28$ 矩阵中展平每个图像\n",
    "变成一个固定长度的 $784$-维向量，\n",
    "然后用完全连接的层处理它们。\n",
    "现在我们已经掌握了卷积层，\n",
    "我们可以在图像中保留空间结构。\n",
    "用卷积层代替密集层的另一个好处是，\n",
    "我们将享受更简约的模型（需要的参数要少得多）。\n",
    "\n",
    "在本节中，我们将介绍LeNet，\n",
    "在最早发表的卷积神经网络中\n",
    "因其在计算机视觉任务中的表现而引起广泛关注。\n",
    "该模型由Yann Lecun介绍（并以其命名），\n",
    "后来，美国电话电报公司贝尔实验室的一名研究员，\n",
    "为了识别图像中的手写数字\n",
    "[LeNet5](http://yann.lecun.com/exdb/lenet/)。\n",
    "这部作品代表了顶峰\n",
    "这项技术已经进行了十年的研究。\n",
    "1989年，乐村发表了第一篇成功的研究论文\n",
    "通过反向传播训练卷积神经网络。\n",
    "\n",
    "\n",
    "当时LeNet取得了优异的成绩\n",
    "匹配支持向量机（SVMs）的性能，\n",
    "然后是监督学习中占主导地位的方法。\n",
    "LeNet特最终适应了识别数字\n",
    "自动取款机上的存款。\n",
    "时至今日，一些自动取款机仍在运行该代码\n",
    "Yann和他的同事Leon Bottou在20世纪90年代写的！\n",
    "\n",
    "\n",
    "## LeNet\n",
    "\n",
    "从高层次上讲，LeNet由三部分组成：\n",
    "(i) 由两个卷积层组成的卷积编码器；和\n",
    "(ii) 由三个完全相连的层组成的致密块体；\n",
    "架构总结如下 :numref:`img_lenet`.\n",
    "\n",
    "![Data flow in LeNet 5. The input is a handwritten digit, the output a probability over 10 possible outcomes.](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/lenet.svg)\n",
    "\n",
    ":label:`img_lenet`\n",
    "\n",
    "\n",
    "每个卷积块中的基本单位\n",
    "是一个卷积层，一个S形激活函数，\n",
    "以及随后的平均池操作。\n",
    "请注意，虽然ReLUs和max-pooling工作得更好，\n",
    "这些发现在90年代还没有被发现。\n",
    "每个卷积层使用 $5\\times 5$ 的内核\n",
    "还有一个S形激活函数。\n",
    "这些层映射空间排列的输入\n",
    "到多个二维要素地图，通常\n",
    "增加频道的数量。\n",
    "第一卷积层有6个输出通道，\n",
    "而第二个有16个。\n",
    "每个 $2\\times2$ 池操作（步骤2）\n",
    "通过空间下采样将维度降低了$4$。\n",
    "卷积块发出的输出大小如下所示：\n",
    "（批次大小、通道、高度、宽度）。\n",
    "\n",
    "为了传递卷积块的输出\n",
    "到完全连接的块，\n",
    "我们必须把小批量中的每一个例子都展平。\n",
    "换句话说，我们接受这个4D输入并转换它\n",
    "进入完全连接层所需的二维输入：\n",
    "作为提醒，我们想要的2D表现\n",
    "使用第一个维度索引minibatch中的示例\n",
    "第二步给出每个例子的平面向量表示。\n",
    "LeNet's的全连接层块有三个全连接层，\n",
    "分别有120、84和10个输出。\n",
    "因为我们还在进行分类，\n",
    "10维输出层对应\n",
    "到可能的输出类的数量。\n",
    "\n",
    "在你真正理解的时候\n",
    "LeNet内部发生的事情可能需要一些努力，\n",
    "希望下面的代码片段能说服您\n",
    "在现代深度学习图书馆中实施这样的模式\n",
    "非常简单。\n",
    "我们只需要实例化一个 `Sequential` 块\n",
    "并将适当的层连接在一起。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.basicdataset.cv.classification.*;\n",
    "import ai.djl.metric.*;\n",
    "import org.apache.commons.lang3.ArrayUtils;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Engine.getInstance().setRandomSeed(1111);\n",
    "\n",
    "NDManager manager = NDManager.newBaseManager();\n",
    "\n",
    "SequentialBlock block = new SequentialBlock();\n",
    "\n",
    "block\n",
    "    .add(Conv2d.builder()\n",
    "                .setKernelShape(new Shape(5, 5))\n",
    "                .optPadding(new Shape(2, 2))\n",
    "                .optBias(false)\n",
    "                .setFilters(6)\n",
    "                .build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Pool.avgPool2dBlock(new Shape(5, 5), new Shape(2, 2), new Shape(2, 2)))\n",
    "    .add(Conv2d.builder()\n",
    "                .setKernelShape(new Shape(5, 5))\n",
    "                .setFilters(16).build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Pool.avgPool2dBlock(new Shape(5, 5), new Shape(2, 2), new Shape(2, 2)))\n",
    "    // Blocks.batchFlattenBlock() 将转换形状的输入（批次大小、通道、高度、宽度）\n",
    "    // 输入形状（批量大小,通道*高度*宽度）\n",
    "    .add(Blocks.batchFlattenBlock())\n",
    "    .add(Linear\n",
    "                .builder()\n",
    "                .setUnits(120)\n",
    "                .build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Linear\n",
    "                .builder()\n",
    "                .setUnits(84)\n",
    "                .build())\n",
    "    .add(Activation::sigmoid)\n",
    "    .add(Linear\n",
    "                .builder()\n",
    "                .setUnits(10)\n",
    "                .build());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们对最初的模型有点随意，\n",
    "去除最后一层中的高斯激活。\n",
    "除此之外，这个网络匹配\n",
    "最初的LeNet5架构。我们还创建了模型和\n",
    "Trainer对象，以便我们初始化结构一次。\n",
    "\n",
    "通过单个通道（黑和白）\n",
    "$28 \\times 28$ 的网络图像\n",
    "并在每一层打印输出形状，\n",
    "我们可以检查模型以确保\n",
    "它的行为符合\n",
    "我们期待的是:numref:`img_lenet_vert`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float lr = 0.9f;\n",
    "Model model = Model.newInstance(\"cnn\");\n",
    "model.setBlock(block);\n",
    "\n",
    "Loss loss = Loss.softmaxCrossEntropyLoss();\n",
    "\n",
    "Tracker lrt = Tracker.fixed(lr);\n",
    "Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build();\n",
    "\n",
    "DefaultTrainingConfig config = new DefaultTrainingConfig(loss).optOptimizer(sgd) // 优化器（损失函数）\n",
    "        .optDevices(Engine.getInstance().getDevices(1)) // 单个GPU\n",
    "        .addEvaluator(new Accuracy()) // 模型精度\n",
    "        .addTrainingListeners(TrainingListener.Defaults.basic());\n",
    "\n",
    "Trainer trainer = model.newTrainer(config);\n",
    "\n",
    "NDArray X = manager.randomUniform(0f, 1.0f, new Shape(1, 1, 28, 28));\n",
    "trainer.initialize(X.getShape());\n",
    "\n",
    "Shape currentShape = X.getShape();\n",
    "\n",
    "for (int i = 0; i < block.getChildren().size(); i++) {\n",
    "    Shape[] newShape = block.getChildren().get(i).getValue().getOutputShapes(new Shape[]{currentShape});\n",
    "    currentShape = newShape[0];\n",
    "    System.out.println(block.getChildren().get(i).getKey() + \" layer output : \" + currentShape);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请注意，表示的高度和宽度\n",
    "在整个卷积块的每一层\n",
    "减少（与上一层相比）。\n",
    "第一个卷积层使用 $2$ 像素的填充\n",
    "以补偿高度和宽度的减少\n",
    "否则，使用 $5 \\times 5$ 会导致这种情况。\n",
    "相比之下，第二个卷积层放弃了填充，\n",
    "因此，高度和宽度都减少了 $4$ 像素。\n",
    "当我们沿着一层层往上爬，\n",
    "通道的数量逐层增加\n",
    "从输入中的1到第一个卷积层后的6\n",
    "第二层之后是16层。\n",
    "然而，每个池层的高度和宽度减半。\n",
    "最后，每个完全连接的层降低了维度，\n",
    "最终发出一个输出，其维数\n",
    "匹配类的数量。\n",
    "\n",
    "![Compressed notation for LeNet5](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/lenet-vert.svg)\n",
    "\n",
    ":label:`img_lenet_vert`\n",
    "\n",
    "\n",
    "## 数据采集和训练\n",
    "\n",
    "既然我们已经实现了这个模型，\n",
    "让我们做一个实验，看看LeNet在时尚界的表现如何。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 256;\n",
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 10);\n",
    "double[] trainLoss;\n",
    "double[] testAccuracy;\n",
    "double[] epochCount;\n",
    "double[] trainAccuracy;\n",
    "\n",
    "epochCount = new double[numEpochs];\n",
    "\n",
    "for (int i = 0; i < epochCount.length; i++) {\n",
    "    epochCount[i] = (i + 1);\n",
    "}\n",
    "\n",
    "FashionMnist trainIter = FashionMnist.builder()\n",
    "        .optUsage(Dataset.Usage.TRAIN)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "\n",
    "\n",
    "FashionMnist testIter = FashionMnist.builder()\n",
    "        .optUsage(Dataset.Usage.TEST)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "                            \n",
    "trainIter.prepare();\n",
    "testIter.prepare();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "虽然卷积网络的参数很少，\n",
    "它们的计算成本可能还会更高\n",
    "比类似的深层多层感知器\n",
    "因为每个参数都参与了更多的工作\n",
    "乘法。\n",
    "如果你可以访问GPU，这可能是一个好时机\n",
    "把它付诸行动，加快训练。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "训练函数 `trainingChapter6` 也类似\n",
    "至 :numref:`sec_softmax_scratch` 中定义的 `trainChapter3` 。\n",
    "因为我们将实现多层次的网络\n",
    "今后，我们将主要依靠DJL。\n",
    "以下列车功能采用DJL模型\n",
    "作为输入，并进行相应的优化。\n",
    "我们初始化模型参数\n",
    "在块上使用Xavier初始值设定项。\n",
    "就像MLP一样，我们的损失函数是交叉熵，\n",
    "我们通过小批量随机梯度下降来最小化它。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public void trainingChapter6(ArrayDataset trainIter, ArrayDataset testIter,\n",
    "             int numEpochs, Trainer trainer) throws IOException, TranslateException {\n",
    "\n",
    "    double avgTrainTimePerEpoch = 0;\n",
    "    Map<String, double[]> evaluatorMetrics = new HashMap<>();\n",
    "\n",
    "    trainer.setMetrics(new Metrics());\n",
    "\n",
    "    EasyTrain.fit(trainer, numEpochs, trainIter, testIter);\n",
    "\n",
    "    Metrics metrics = trainer.getMetrics();\n",
    "\n",
    "    trainer.getEvaluators().stream()\n",
    "        .forEach(evaluator -> {\n",
    "            evaluatorMetrics.put(\"train_epoch_\" + evaluator.getName(), metrics.getMetric(\"train_epoch_\" + evaluator.getName()).stream()\n",
    "                    .mapToDouble(x -> x.getValue().doubleValue()).toArray());\n",
    "            evaluatorMetrics.put(\"validate_epoch_\" + evaluator.getName(), metrics.getMetric(\"validate_epoch_\" + evaluator.getName()).stream()\n",
    "                    .mapToDouble(x -> x.getValue().doubleValue()).toArray());\n",
    "        });\n",
    "\n",
    "    avgTrainTimePerEpoch = metrics.mean(\"epoch\");\n",
    "\n",
    "    trainLoss = evaluatorMetrics.get(\"train_epoch_SoftmaxCrossEntropyLoss\");\n",
    "    trainAccuracy = evaluatorMetrics.get(\"train_epoch_Accuracy\");\n",
    "    testAccuracy = evaluatorMetrics.get(\"validate_epoch_Accuracy\");\n",
    "\n",
    "    System.out.printf(\"loss %.3f,\" , trainLoss[numEpochs-1]);\n",
    "    System.out.printf(\" train acc %.3f,\" , trainAccuracy[numEpochs-1]);\n",
    "    System.out.printf(\" test acc %.3f\\n\" , testAccuracy[numEpochs-1]);\n",
    "    System.out.printf(\"%.1f examples/sec \\n\", trainIter.size() / (avgTrainTimePerEpoch / Math.pow(10, 9)));\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在让我们来训练这个模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainingChapter6(trainIter, testIter, numEpochs, trainer);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Contour Gradient Descent.](https://d2l-java-resources.s3.amazonaws.com/img/chapter_convolution_neural_network_leNet.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length];\n",
    "\n",
    "Arrays.fill(lossLabel, 0, trainLoss.length, \"train loss\");\n",
    "Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, \"train acc\");\n",
    "Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length,\n",
    "                trainLoss.length + testAccuracy.length + trainAccuracy.length, \"test acc\");\n",
    "\n",
    "Table data = Table.create(\"Data\").addColumns(\n",
    "    DoubleColumn.create(\"epoch\", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))),\n",
    "    DoubleColumn.create(\"metrics\", ArrayUtils.addAll(trainLoss, ArrayUtils.addAll(trainAccuracy, testAccuracy))),\n",
    "    StringColumn.create(\"lossLabel\", lossLabel)\n",
    ");\n",
    "\n",
    "render(LinePlot.create(\"\", data, \"epoch\", \"metrics\", \"lossLabel\"), \"text/html\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n",
    "\n",
    "* ConvNet是一种采用卷积层的网络。\n",
    "* 在ConvNet中，我们交错卷积、非线性和（通常）池操作。\n",
    "* 这些卷积块通常被布置成在增加通道数量的同时逐渐降低表示的空间分辨率。\n",
    "* 在传统的convnet中，由卷积块编码的表示在发射输出之前由一个（或多个）密集层处理。\n",
    "* LeNet可以说是第一个成功部署此类网络的。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 将平均池替换为最大池。会发生什么？\n",
    "1. 尝试基于LeNet构建更复杂的网络，以提高其精度。\n",
    "    * 调整卷积窗口的大小。\n",
    "    * 调整输出通道的数量。\n",
    "    * 调整激活功能（ReLU？）。\n",
    "    * 调整卷积层数。\n",
    "    * 调整完全连接的层的数量。\n",
    "    * 调整学习率和其他培训细节（初始化、历次等）\n",
    "1. 在原始MNIST数据集上尝试改进的网络。\n",
    "1. 显示第一层和第二层LeNet对不同输入（例如毛衣、外套）的激活情况。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
